package com.ellecity06.cwhiskymall.ui.home

import android.content.Context
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.behavior.CustomBehavior
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.addLinearDecoration
import com.ellecity06.common.ktx.colorResToColorId
import com.ellecity06.common.ktx.dp2px
import com.ellecity06.common.ktx.launchActivity
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.sp2px
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.common.ktx.toAmount
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.HomeCategoryAdapter
import com.ellecity06.cwhiskymall.adapter.ImageBannerAdapter
import com.ellecity06.cwhiskymall.adapter.LazyFragmentPagerAdapter
import com.ellecity06.cwhiskymall.adapter.NewerGoodAdapter
import com.ellecity06.cwhiskymall.adapter.SelfGoodAdapter
import com.ellecity06.cwhiskymall.bean.response.AppMenuSettingRespone
import com.ellecity06.cwhiskymall.bean.response.SurplusContributionResonse
import com.ellecity06.cwhiskymall.databinding.FragmentHomeBinding
import com.ellecity06.cwhiskymall.storage.AppStorage
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.MainActivity
import com.ellecity06.cwhiskymall.ui.consumer_gift.ConsumerGiftActivity
import com.ellecity06.cwhiskymall.ui.invite.InviteFriendActivity
import com.ellecity06.cwhiskymall.ui.mine.newer.NewerLearningActivity
import com.ellecity06.cwhiskymall.ui.search.SearchActivity
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.ellecity06.cwhiskymall.utils.radiusBackground
import com.ellecity06.cwhiskymall.utils.textStyle
import com.ellecity06.cwhiskymall.view.dialog.ActivityDialog
import com.ellecity06.cwhiskymall.view.dialog.NewerDialog
import com.ellecity06.cwhiskymall.view.dialog.NewerGuideDialog
import com.ellecity06.cwhiskymall.view.dialog.ReceiveDialog
import com.ellecity06.cwhiskymall.view.tab.HomeMenuTab
import com.google.android.material.appbar.AppBarLayout
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import kotlin.math.abs

/**
 * @author ellecity06
 * @time 2024/10/22 14:49
 * @des 首页
 */
class HomeFragment : BaseMvvmFragment<FragmentHomeBinding, HomeViewModel>(),
    SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private val newerGoodAdapter: NewerGoodAdapter by lazy { NewerGoodAdapter() }
    private val selfGoodAdapter: SelfGoodAdapter by lazy { SelfGoodAdapter() }
    private val homeCategoryAdapter: HomeCategoryAdapter by lazy { HomeCategoryAdapter(binding.rvCategory) }
    private lateinit var commonNavigatorAdapter: CommonNavigatorAdapter
    private var isLoad = false

    companion object {
        @JvmStatic
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }

    }

    private var menuShow = true
    private fun hideMenu() {
        if (menuShow) {
            menuShow = false
            binding.layoutMenu.animate().translationX(100F.dp2px().toFloat()).alpha(0f).withLayer()
                .setDuration(1000).start()
        }

    }

    private fun showMenu() {
        if (!menuShow) {
            menuShow = true
            binding.layoutMenu.animate().translationX(0f).alpha(1f).withLayer().setDuration(1000)
                .start()

        }

    }

    private val menuFlow = MutableStateFlow(0)
    private var lastVerticalOffset = 0

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        statusBar(binding.viewStatusBar)
        super.initView()
        binding.refreshLayout.setColorSchemeResources(R.color.colorAccent)
        binding.refreshLayout.setOnRefreshListener(this)

        binding.appBarLayout.addOnOffsetChangedListener { _, verticalOffset ->
            binding.refreshLayout.isEnabled = verticalOffset >= 0
            if (verticalOffset != 0 && abs(verticalOffset) != binding.appBarLayout.totalScrollRange && lastVerticalOffset != verticalOffset) {
                lastVerticalOffset = verticalOffset
                hideMenu()
            }
            lifecycleScope.launchWhenCreated {
                menuFlow.emit(verticalOffset)
            }

        }
        binding.appBarLayout.post {
            val params: CoordinatorLayout.LayoutParams =
                binding.appBarLayout.layoutParams as CoordinatorLayout.LayoutParams
            val behavior = params.behavior as CustomBehavior
            behavior.setDragCallback(object : AppBarLayout.Behavior.DragCallback() {
                override fun canDrag(appBarLayout: AppBarLayout): Boolean {
                    return true
                }

            })
        }
        binding.includeNewer.rvNewerGood.apply {
            layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
            addLinearDecoration(size = R.dimen.dp_8)
            adapter = newerGoodAdapter
        }
        //金刚区
        binding.rvCategory.apply {
            setHasFixedSize(true)
            layoutManager = GridLayoutManager(requireActivity(), 4)
//            addLinearDecoration(size =
//            addItemDecoration(HorizontalScrollBarDecoration())
            adapter = homeCategoryAdapter
        }
        //轮播
        binding.banner.apply {
            indicator = CircleIndicator(activity)
            setLoopTime(5000)
            setIntercept(false)
        }
        // 自营爆款专区
        binding.selfLayout.rvSelfGood.apply {
            layoutManager = GridLayoutManager(requireActivity(), 3)
            addGridDecoration(size = R.dimen.dp_5)
            adapter = selfGoodAdapter
        }
        initEvent()
    }

    private fun initEvent() {
        newerGoodAdapter.setOnItemClickListener { _, _, position ->
            val item = newerGoodAdapter.getItem(position)
            WebHelper.goodDetails(requireActivity(), item?.goodSpuid)
//            val newerCategoryId = viewModel.getNewerCategoryId()
//            if (newerCategoryId != null) {
//                launchActivity<NewerGoodActivity>(Pair("categoryId", newerCategoryId))
//            }
        }
        selfGoodAdapter.setOnItemClickListener { _, _, position ->
            val item = selfGoodAdapter.getItem(position)
            WebHelper.goodDetails(requireActivity(), item?.goodSpuid)
        }
        homeCategoryAdapter.setOnItemClickListener { _, _, position ->
            val item = homeCategoryAdapter.getItem(position)
            val mainAct = requireActivity() as MainActivity
            mainAct.chooseClassify(item?.settingId ?: 0)
        }
        binding.includeNewer.ivInvite.setOnClickListener(this)
        binding.selfLayout.tvGoMore.setOnClickListener(this)
        binding.ivAdv1.setOnClickListener(this)
        binding.layoutSearch.setOnClickListener(this)
//        binding.includeNewer.layoutSingle.setOnClickListener(this)
        binding.ivShopCart.setOnClickListener(this)
        binding.viewFirstOrder.setOnClickListener(this)
        binding.ivCustomer.setOnClickListener(this)
        binding.includeNewer.viewMore.setOnClickListener(this)
        binding.includeNewer.flNewerGood.setOnClickListener(this)
        binding.ivNewerLearning.setOnClickListener(this)
        binding.ivShop9000.setOnClickListener(this)

    }

    override fun lazyInit() {
        sendFetchIntent()
        observeViewModel()
//        showActivityDialog()
    }

    private fun showActivityDialog(data: AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO) {
        ActivityDialog(requireActivity()) { WebHelper.toDionysusPage(requireActivity(), data.settingId ?: 0) }.show()
    }

    private fun sendFetchIntent() {
        lifecycleScope.launch {
            viewModel.intentChannel.send(HomeIntent.FetchHomeData)
            viewModel.intentChannel.send(HomeIntent.FetchSurplus)
        }
    }

    private fun observeViewModel() {
        lifecycleScope.launch {
            menuFlow.debounce(300)
                .collect {
                    showMenu()
                }
        }
        viewModel.state.observeEvent(this) {
            when (it) {
                is HomeState.Error -> {
                    binding.empty.root.visibility = View.VISIBLE
                    binding.content.visibility = View.GONE
                    finishRefresh()
                }

                is HomeState.Success -> {
                    binding.empty.root.visibility = View.GONE
                    binding.content.visibility = View.VISIBLE
                    finishRefresh()
                }

                is HomeState.DionysusData -> {
                    binding.layoutShop9000.visibility = UserStorage.upVisible()
                    val image =
                        if (it.data.customImage == null || it.data.customImage.isEmpty()) it.data.image else it.data.customImage
                    binding.ivShop9000.load(requireActivity(), image)
                }

                is HomeState.NewerData -> {
                    setNewerData(it.data)
                }

                is HomeState.BannerData -> {
                    setBannerData(it.data)
                }

                is HomeState.CategoryData -> {
                    setCategoryData(it.data)
                }

                is HomeState.Adv1Data -> {
                    setAdvData(it.data)
                }

                is HomeState.SelfStoreData -> {
                    setSelfData(it.data)
                }

                is HomeState.MenuTabData -> {

                    setMenuData(it.list, it.fragments)
                }

                is HomeState.SurplusContribution -> {
                    setSurplusData(it.data)
                }

                is HomeState.ReceiveSuccess -> {
                    receiveDialog?.dismiss()
                }

                is HomeState.FetchUserSuccess -> {
                    if (requireActivity() is MainActivity){
                        (requireActivity() as MainActivity).refreshBottomTab()
                    }
                    setIsNewer()
                    showNewerDialog()
                }
                is HomeState.ShowActivityDialog -> {
                    showActivityDialog(it.data)
                }

                else -> {}
            }
        }
    }

    // 是否已经领过新人首单福利
    private var received: Boolean = false

    // 设置新人首单数据
    private fun setSurplusData(data: SurplusContributionResonse) {
        received = !(data.receive ?: false)

        if (UserStorage.isHasUp()) {
            if (data.show == true) {
                AppStorage.isTodayFirstLogin {
                    NewerGuideDialog(requireActivity()).show()
                }
            }
            binding.viewFirstOrder.visibility = if (data.show == true) View.VISIBLE else View.GONE
        } else {
            binding.viewFirstOrder.visibility = View.GONE
        }

        binding.tvSurplusAmount.text = data.surplusContribution?.toAmount()

    }

    private val newerDialog: NewerDialog by lazy {
        NewerDialog(requireActivity()) {
            launchNewerGoodActivity()
        }
    }

    fun showNewerDialog() {
        if (isResumed && !UserStorage.isVip()) {
            newerDialog.show()
        }

    }

    private fun finishRefresh() {
        if (binding.refreshLayout.isRefreshing) {
            binding.refreshLayout.isRefreshing = false
        }

    }

    /**
     * 设置轮播图数据
     */
    private fun setBannerData(data: List<AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO>) {
        if (data.isNotEmpty()) {
            binding.banner.visibility = View.VISIBLE
            binding.banner.setAdapter(ImageBannerAdapter(data, click = ::onBannerItemClick))
            binding.banner.start()
        }
    }

    private fun setAdvData(data: AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO) {
        binding.ivAdv1.visibility = View.VISIBLE
        val image =
            if (data.customImage == null || data.customImage.isEmpty()) data.image else data.customImage
        binding.ivAdv1.load(requireActivity(), image)

    }

    /**
     * 轮播图点击
     */
    private fun onBannerItemClick(bannerSettingVOS: AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO) {
        when (bannerSettingVOS.myJumpType) {
            // 新人首单
            1 -> {
                WebHelper.toNewerGoosList(requireActivity(), bannerSettingVOS.settingId ?: 0,0)
            }
            // 酒神
            2 -> {
                WebHelper.toDionysusPage(requireActivity(), bannerSettingVOS.settingId ?: 0)
            }
            // 贡献金打卡
            3 -> {
//                WebHelper.toDionysusPage(requireActivity(), bannerSettingVOS.settingId ?: 0)
                launchActivity<ConsumerGiftActivity>()
            }
            else -> {
                WebHelper.subjectGoods(requireActivity(), bannerSettingVOS.settingId)
            }
        }

    }

    private var newerGoodId: Int? = null

    /**
     * 设置新人数据
     */
    private fun setNewerData(data: AppMenuSettingRespone.SettingWebLayoutVOS) {
        // 判断一下显示规则  大于4显示列表，否则只显示第一个
        val goodsVOList = data.goodsVOList ?: mutableListOf()
        if (goodsVOList.isNotEmpty()) {
            if (goodsVOList.size > 4) {
                binding.includeNewer.layoutMultiple.visibility = View.VISIBLE
                binding.includeNewer.layoutSingle.visibility = View.GONE
                // 显示更多
//                binding.includeNewer.viewMore.visibility = View.VISIBLE

                // 显示多商品
                newerGoodAdapter.submitList(goodsVOList)

            } else {
                // 显示单商品
                newerGoodId = goodsVOList[0].goodSpuid
                // 隐藏更多
//                binding.includeNewer.viewMore.visibility = View.GONE
                binding.includeNewer.layoutMultiple.visibility = View.GONE
                binding.includeNewer.layoutSingle.visibility = View.VISIBLE
                setSingleGoodData(goodsVOList[0])
            }
        }
        setIsNewer()

    }

    override fun onResume() {
        super.onResume()
//        val show198: Boolean by lazy { UserStorage.user?.unlockStatus == 0 }
//        if (show198) {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(HomeIntent.UpdateUser)
//            }
        }
    }

    private fun setIsNewer() {
        if (!UserStorage.isVip()) {
            binding.includeNewer.ivNewerText.setImageResource(R.mipmap.icon_newer_text)
            binding.includeNewer.ivInvite.setImageResource(R.mipmap.bg_home_newer_bottom)
            binding.includeNewer.tv5388.visibility = View.GONE
        } else {
            binding.includeNewer.ivNewerText.setImageResource(R.mipmap.icon_xiaofeibutie)
            binding.includeNewer.ivInvite.setImageResource(R.mipmap.bg_home_newer_bottom2)
//            binding.includeNewer.tv5388.visibility = View.VISIBLE
            binding.includeNewer.tv5388.visibility = UserStorage.upVisible()
        }

        binding.includeNewer.ivInvite.visibility = UserStorage.upVisible()
        binding.ivNewerLearning.visibility = UserStorage.upVisible()
//        binding.layoutShop9000.visibility = UserStorage.upVisible()
    }

    /**
     * 设置新人首单单商品数据
     */
    private fun setSingleGoodData(goodsVO: AppMenuSettingRespone.SettingWebLayoutVOS.GoodsVO) {
        binding.includeNewer.ivGoodImg.load(requireActivity(), goodsVO.spuImage, 8F)
        binding.includeNewer.tvPrice.text = "￥${goodsVO.salesPrice}"
        // 有邀请人显示贡献金
        if (UserStorage.isHasUp() && UserStorage.isVip()) {
            binding.includeNewer.tvContribution.text = buildSpannedString {
                scale(0.55F) {
                    append("赠送")
                }
                append(goodsVO.contribution ?: "")
                scale(0.55F) {
                    append("贡献金")
                }
            }
            binding.includeNewer.tvPrice.visibility = View.VISIBLE
            binding.includeNewer.tvNewerGoodTag.text = " | 正品保障 丨 极速发货"
        } else {
            binding.includeNewer.tvContribution.text = buildSpannedString {
                if (UserStorage.isHasUp()) {
                    scale(0.55F) {
                        append("会员专享价格：")
                    }
                }
                append("￥${goodsVO.salesPrice ?: 0.00}")

            }
            binding.includeNewer.tvPrice.visibility = View.GONE
            binding.includeNewer.tvNewerGoodTag.text = " 正品保障 丨 极速发货"
        }
        val nameSpan = buildSpannedString {
            if (goodsVO.goodsSource == 0) {
                radiusBackground(R.color.colorAccent.colorResToColorId(), 4) {
                    append("自营")
                }
            }
            textStyle(size = 15F.sp2px(), style = Typeface.BOLD) {
                append(" ${goodsVO.spuName}")
            }
        }
        binding.includeNewer.tvGoodsName.text = nameSpan
        binding.includeNewer.tvStock.text = "剩余库存：${goodsVO.spuStock}"
        binding.includeNewer.tvMarketPrice.visibility =
            if (goodsVO.marketPrice == null || UserStorage.isVip()) View.INVISIBLE else View.VISIBLE
        binding.includeNewer.tvMarketPrice.text = "零售价：${goodsVO.marketPrice ?: 0.00}元"
        binding.includeNewer.tvMarketPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        binding.includeNewer.tvMarketPrice.paint.isAntiAlias = true

    }

    private fun setCategoryData(data: AppMenuSettingRespone.SettingWebLayoutVOS) {
        homeCategoryAdapter.submitList(data.detailVOList)
    }

    /**
     * 设置自营店铺数据
     */
    private fun setSelfData(data: AppMenuSettingRespone.SettingWebLayoutVOS) {
        if (data.detailVOList!![0].image == null || data.detailVOList[0].image!!.isEmpty()) {
            binding.selfLayout.ivHeader.setImageResource(R.mipmap.bg_self_store_top)
        } else {
            binding.selfLayout.ivHeader.load(requireActivity(), data.detailVOList!![0]?.image)
        }

        if (data.goodsVOList != null && data.goodsVOList.size > 3) {
            selfGoodAdapter.submitList(data.goodsVOList.subList(0, 3))
        } else {
            selfGoodAdapter.submitList(data.goodsVOList)
        }

    }

    private fun setMenuData(
        list: List<AppMenuSettingRespone.SettingWebLayoutVOS.DetailVO>,
        fragments: MutableList<Fragment>
    ) {

        // 商品列表菜单
        val commonNavigator = CommonNavigator(requireActivity())
        commonNavigatorAdapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return list.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val tab = HomeMenuTab(context, list, index)
                tab.setOnClickListener { binding.viewpager.setCurrentItem(index, false) }
                return tab
            }

            override fun getIndicator(context: Context): IPagerIndicator? {
                return null
            }
        }
        commonNavigator.adapter = commonNavigatorAdapter
        commonNavigator.isAdjustMode = false
        binding.menuTab.navigator = commonNavigator
        binding.viewpager.offscreenPageLimit = fragments.size
        ViewPagerHelper.bind(binding.menuTab, binding.viewpager)
        val myFragmentPagerAdapter = LazyFragmentPagerAdapter(childFragmentManager, fragments)
        binding.viewpager.adapter = myFragmentPagerAdapter

    }

    override fun inflateBinding(
        inflater: LayoutInflater, container: ViewGroup?
    ): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, container, false)
    }

    override fun onRefresh() {
        sendFetchIntent()
        if (requireActivity() is MainActivity) {
            (requireActivity() as MainActivity).fetchH5Host()
        }
    }

    private var receiveDialog: ReceiveDialog? = null
    override fun onClick(view: View?) {
        when (view?.id) {
            binding.layoutSearch.id -> {
                launchActivity<SearchActivity>()
            }

            binding.selfLayout.tvGoMore.id -> {
                WebHelper.superCostEffective(requireActivity(), viewModel.getJuHuaSuanId())
            }

            binding.ivAdv1.id -> {
                WebHelper.subjectGoods(requireActivity(), viewModel.getZuanTiId())
            }

            binding.includeNewer.ivInvite.id -> {
                launchActivity<InviteFriendActivity>()
            }

            binding.includeNewer.layoutSingle.id -> {
//                newerGoodId?.let {
//                    WebHelper.goodDetails(requireActivity(), it)
//                }

            }

            binding.viewFirstOrder.id -> {
                receiveDialog = ReceiveDialog(requireActivity()) {
                    lifecycleScope.launchWhenCreated {
                        viewModel.intentChannel.send(HomeIntent.ReceiveWelfare)
                    }
                }
                receiveDialog?.show(received)
            }

            binding.ivShopCart.id -> {
                WebHelper.toShopCart(requireActivity())
            }

            binding.ivCustomer.id -> {
                WebHelper.toKefu(requireActivity())
            }

            binding.includeNewer.viewMore.id -> {
                launchNewerGoodActivity()

            }

            binding.includeNewer.flNewerGood.id -> {
                launchNewerGoodActivity()
            }

            binding.ivNewerLearning.id -> {
                launchActivity<NewerLearningActivity>()
            }

            binding.ivShop9000.id -> {
                WebHelper.toDionysusPage(requireActivity(), viewModel.getDionysusZoneId())
            }
        }
    }

    /**
     * 打开新人首单或者消费补贴列表页面
     */
    private fun launchNewerGoodActivity() {
        val newerCategoryId = viewModel.getNewerCategoryId()
        WebHelper.toNewerGoosList(requireActivity(), newerCategoryId ?: 0)
//        if (newerCategoryId != null) {
//            launchActivity<NewerGoodActivity>(Pair("categoryId", newerCategoryId))
//        }
    }


}